<template>
  <transition name="drone-overlay">
    <div v-if="visible && selectedDrone" class="drone-overlay">
      <div class="overlay-panel overlay-video">
        <div class="panel-header">
          <div class="panel-title">
            <span>实时画面</span>
            <el-tag
              size="small"
              class="status-tag"
              :type="getStatusType(selectedDrone.status)"
            >
              {{ selectedDrone.status }}
            </el-tag>
          </div>
          <span class="video-meta">
            电量 {{ toPercent(selectedDrone.battery) }} ·
            {{ coordinateText }}
          </span>
        </div>
        <div class="video-wrapper">
          <DroneVideoPlayer
            v-if="droneStreamUrl"
            :streamUrl="droneStreamUrl"
            :autoplay="true"
          />
          <img v-else :src="selectedDrone.currentFrame" alt="无人机实时画面" />
        </div>
      </div>

      <div
        class="overlay-panel overlay-tabs"
        :class="{ minimized: isMinimized }"
      >
        <div class="tabs-header" v-if="!isMinimized">
          <div class="tabs-title">
            {{ selectedDrone.name || selectedDrone.id || "无人机" }}
          </div>
          <div class="tabs-actions">
            <i
              class="iconfont icon-suoxiao"
              style="font-size: 13px"
              @click.stop="minimizeOverlay"
            ></i>
            <el-button
              class="tabs-action tabs-close"
              @click.stop="closeOverlay"
            >
              ✖
            </el-button>
          </div>
        </div>
        <el-tabs v-if="!isMinimized" v-model="activeTab" class="control-tabs">
          <el-tab-pane label="飞行参数设置" name="params">
            <div class="tab-inner">
              <div class="info-row">
                <span class="info-label">无人机ID</span>
                <span class="info-value">{{ selectedDrone.id }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">坐标</span>
                <span class="info-value">{{ coordinateText }}</span>
              </div>
              <el-form
                label-width="80px"
                label-position="left"
                class="params-form"
              >
                <el-form-item label="飞行高度">
                  <el-input-number
                    v-model="droneForm.altitude"
                    :min="0"
                    :max="maxAltitude"
                    :step="5"
                  />
                  <span class="unit">m</span>
                </el-form-item>
                <el-form-item label="飞行速度">
                  <el-input-number
                    v-model="droneForm.speed"
                    :min="0"
                    :max="40"
                    :step="1"
                  />
                  <span class="unit">m/s</span>
                </el-form-item>
                <el-form-item label="飞行模式">
                  <el-select v-model="droneForm.mode" placeholder="选择模式">
                    <el-option
                      v-for="item in droneModes"
                      :key="item"
                      :value="item"
                      :label="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="载荷配置">
                  <el-select v-model="droneForm.payload" placeholder="选择载荷">
                    <el-option
                      v-for="item in payloadOptions"
                      :key="item"
                      :value="item"
                      :label="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="失联动作">
                  <el-select
                    v-model="droneForm.lostAction"
                    placeholder="失联动作"
                  >
                    <el-option
                      v-for="item in lostActions"
                      :key="item"
                      :value="item"
                      :label="item"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <div class="params-footer">
                <el-button type="primary" @click="handleSubmit">
                  保存参数
                </el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="任务详情" name="taskDetail">
            <div class="tab-inner task-detail-tab">
              <div v-if="task" class="task-detail-content">
                <!-- 基本信息 -->
                <div class="detail-section">
                  <h4>基本信息</h4>
                  <div class="info-grid">
                    <div class="info-item">
                      <span class="label">任务名称：</span>
                      <span class="value">{{ task.name }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">任务状态：</span>
                      <span
                        class="value"
                        :class="getStatusClass(task.status)"
                        >{{ getStatusText(task.status) }}</span
                      >
                    </div>
                    <div class="info-item">
                      <span class="label">优先级：</span>
                      <span class="value">{{
                        getPriorityText(task.priority)
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">负责人：</span>
                      <span class="value">{{
                        task.responsible_person || "无"
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">执行类型：</span>
                      <span class="value">{{
                        getExecuteTypeText(task.execute_type)
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">开始时间：</span>
                      <span class="value">{{
                        formatTime(task.start_time)
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">结束时间：</span>
                      <span class="value">{{
                        formatTime(task.end_time) || "未完成"
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">计划时间：</span>
                      <span class="value">{{
                        formatTime(task.scheduled_time) || "立即执行"
                      }}</span>
                    </div>
                  </div>
                </div>

                <!-- 任务描述 -->
                <div class="detail-section" v-if="task.description">
                  <h4>任务描述</h4>
                  <div class="description">
                    {{ task.description }}
                  </div>
                </div>

                <!-- 无人机信息 -->
                <div
                  class="detail-section"
                  v-if="task.task_drones && task.task_drones.length > 0"
                >
                  <h4>无人机信息</h4>
                  <div class="drone-list">
                    <div
                      v-for="taskDrone in task.task_drones"
                      :key="taskDrone.id || taskDrone.drone_id"
                      class="drone-item"
                      :class="{
                        'primary-drone':
                          taskDrone.is_primary || taskDrone.isPrimary,
                      }"
                    >
                      <div class="drone-header">
                        <span class="drone-name">{{
                          taskDrone.drone?.name ||
                          `无人机${taskDrone.drone_id || taskDrone.droneId}`
                        }}</span>
                        <span
                          class="primary-badge"
                          v-if="taskDrone.is_primary || taskDrone.isPrimary"
                          >主用</span
                        >
                      </div>
                      <div class="drone-info">
                        <span class="drone-id"
                          >ID:
                          {{ taskDrone.drone_id || taskDrone.droneId }}</span
                        >
                        <span class="drone-type" v-if="taskDrone.drone?.type"
                          >类型: {{ taskDrone.drone.type }}</span
                        >
                        <span
                          class="drone-status"
                          v-if="taskDrone.drone?.status"
                        >
                          状态:
                          <span :class="getStatusClass(taskDrone.drone.status)">
                            {{ getStatusText(taskDrone.drone.status) }}
                          </span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 航线信息 -->
                <div
                  class="detail-section"
                  v-if="task.task_routes && task.task_routes.length > 0"
                >
                  <h4>航线信息</h4>
                  <div class="route-list">
                    <div
                      v-for="(taskRoute, index) in task.task_routes"
                      :key="taskRoute.id || index"
                      class="route-item"
                    >
                      <div class="route-header">
                        <span class="route-name">{{
                          taskRoute.route?.name || `航线${index + 1}`
                        }}</span>
                        <span class="waypoint-count"
                          >{{
                            taskRoute.route?.waypoints?.length || 0
                          }}
                          个航点</span
                        >
                      </div>
                      <div class="route-info">
                        <div
                          class="waypoints-preview"
                          v-if="
                            taskRoute.route?.waypoints &&
                            taskRoute.route.waypoints.length > 0
                          "
                        >
                          <div
                            v-for="(
                              waypoint, wpIndex
                            ) in taskRoute.route.waypoints.slice(0, 3)"
                            :key="wpIndex"
                            class="waypoint-item"
                          >
                            <span>航点{{ wpIndex + 1 }}: </span>
                            <span>{{
                              formatCoord(waypoint.lat, waypoint.lng)
                            }}</span>
                            <span v-if="waypoint.alt">
                              高度: {{ waypoint.alt }}m</span
                            >
                          </div>
                          <div
                            class="waypoint-more"
                            v-if="taskRoute.route.waypoints.length > 3"
                          >
                            ... 还有
                            {{ taskRoute.route.waypoints.length - 3 }} 个航点
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 检测模型 -->
                <div
                  class="detail-section"
                  v-if="
                    task.detection_model_ids &&
                    task.detection_model_ids.length > 0
                  "
                >
                  <h4>检测模型</h4>
                  <div class="model-list">
                    <div
                      v-for="modelId in task.detection_model_ids"
                      :key="modelId"
                      class="model-item"
                    >
                      <span>模型 ID: {{ modelId }}</span>
                    </div>
                  </div>
                </div>

                <!-- 进度信息 -->
                <div class="detail-section" v-if="task.progress !== undefined">
                  <h4>执行进度</h4>
                  <div class="progress-container">
                    <div class="progress-bar">
                      <div
                        class="progress-fill"
                        :style="{ width: task.progress + '%' }"
                      ></div>
                    </div>
                    <span class="progress-text">{{ task.progress }}%</span>
                  </div>
                </div>
              </div>
              <div v-else class="task-empty">请选择一个任务查看详情</div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="手动控制" name="manual">
            <div class="tab-inner manual-tab">
              <compassMetric />
              <div class="manual-section card transparent">
                <div class="manual-control-head">
                  <h4>手动控制</h4>
                  <span class="manual-subtitle"
                    >使用键盘或点击按钮执行飞行指令</span
                  >
                </div>
                <div class="emergency-controls">
                  <el-button
                    type="success"
                    @click="handlePauseTask"
                    :loading="controlStatus === 'executing'"
                  >
                    起飞
                  </el-button>
                  <el-button
                    type="danger"
                    @click="handleEmergencyLand"
                    :loading="controlStatus === 'executing'"
                  >
                    紧急迫降
                  </el-button>
                  <el-button
                    type="warning"
                    @click="handleReturnToHome"
                    :loading="controlStatus === 'executing'"
                  >
                    原地返航
                  </el-button>
                </div>

                <div class="connection-controls" style="margin-bottom: 16px">
                  <el-button
                    type="primary"
                    @click="connectDrone"
                    :disabled="isConnected || controlStatus === 'connecting'"
                    :loading="controlStatus === 'connecting'"
                  >
                    连接无人机
                  </el-button>
                  <el-button
                    type="info"
                    @click="disconnectDrone"
                    :disabled="
                      !isConnected || controlStatus === 'disconnecting'
                    "
                    :loading="controlStatus === 'disconnecting'"
                  >
                    断开连接
                  </el-button>
                  <el-tag
                    :type="isConnected ? 'success' : 'info'"
                    size="small"
                    style="margin-left: 10px"
                  >
                    {{ isConnected ? "已连接" : "未连接" }}
                  </el-tag>
                </div>
                <div class="manual-grid">
                  <div
                    v-for="control in computedManualControls"
                    :key="control.id"
                    class="manual-item"
                    :class="{ active: isControlActive(control.id) }"
                    @click="handleControlClick(control.id)"
                  >
                    <span class="control-name">{{ control.label }}</span>
                    <span class="control-keys">{{ control.displayKeys }}</span>
                  </div>
                </div>
                <div class="manual-feedback">
                  <div class="feedback-row">
                    <span class="feedback-label">执行状态</span>
                    <span class="feedback-value">{{
                      controlStatus || droneControlStatus
                    }}</span>
                  </div>
                  <div class="feedback-row">
                    <span class="feedback-label">指令反馈</span>
                    <span class="feedback-value">{{ controlFeedback }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <button
        v-if="isMinimized"
        class="overlay-expand-button"
        @click.stop="restoreOverlay"
      >
        <i class="iconfont icon-zhankai"></i>
      </button>
    </div>
  </transition>
</template>

<script setup>
import { computed, ref, watch, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import compassMetric from "./compassMetric.vue";
import DroneVideoPlayer from "@/components/DroneVideoPlayer.vue";
import { droneService } from "@/api";

const props = defineProps({
  modelValue: { type: Boolean, required: true },
  selectedDrone: { type: Object, default: null },
  task: { type: Object, default: null },
  droneForm: { type: Object, required: true },
  droneModes: { type: Array, default: () => [] },
  payloadOptions: { type: Array, default: () => [] },
  lostActions: { type: Array, default: () => [] },
  manualControls: { type: Array, default: () => [] },
  manualControlStatus: { type: String, default: "" },
  manualControlFeedback: { type: String, default: "" },
  isControlActive: { type: Function, required: true },
  getStatusType: { type: Function, required: true },
  flightDashboardMetrics: { type: Object, default: () => ({}) },
  maxAltitude: { type: Number, default: 500 },
});

const emit = defineEmits(["update:modelValue", "control-click", "submit"]);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const activeTab = ref("manual");
const isMinimized = ref(false);

// 无人机控制相关状态
const isConnected = ref(false);
const droneControlStatus = ref("idle");
const controlStatus = ref("");
const controlFeedback = ref("");
const statusTimer = ref(null);
const dronePoseData = ref({}); // 存储无人机姿态数据

// 视频流地址配置 - 使用 WebRTC 流
const droneStreamUrl = computed(() => {
  // 如果 selectedDrone 有自己的 streamUrl 配置,使用它
  if (props.selectedDrone?.streamUrl) {
    return props.selectedDrone.streamUrl;
  }

  // 根据无人机ID动态生成 WebRTC 流地址
  const droneId = props.selectedDrone?.id || "001";
  const droneIdStr = String(droneId).padStart(3, "0");

  // 使用七牛云 WebRTC 地址格式
  return `webrtc://222.222.95.59:1240/shandong/drone${droneIdStr}`;
});

const isApiSuccess = (result) => {
  if (!result) return false;
  if (typeof result.code !== "undefined" && result.code !== 200) {
    return false;
  }

  if (typeof result.success !== "undefined") {
    return result.success;
  }

  if (result.data && typeof result.data.success !== "undefined") {
    return result.data.success;
  }

  return true;
};

const getApiMessage = (result, fallbackMessage) => {
  return result?.data?.message || result?.message || fallbackMessage;
};

const getPx4Alias = () => {
  if (!props.selectedDrone?.id) {
    return "";
  }
  return `uav_${props.selectedDrone.id}`;
};

// 确保manualControls始终有默认值
const computedManualControls = computed(() => {
  if (props.manualControls && props.manualControls.length > 0) {
    return props.manualControls;
  }
  // 默认手动控制选项
  return [
    { id: "takeoff", label: "起飞", displayKeys: "T" },
    { id: "land", label: "降落", displayKeys: "L" },
    { id: "forward", label: "前进", displayKeys: "↑" },
    { id: "backward", label: "后退", displayKeys: "↓" },
    { id: "left", label: "左移", displayKeys: "←" },
    { id: "right", label: "右移", displayKeys: "→" },
    { id: "ascend", label: "上升", displayKeys: "W" },
    { id: "descend", label: "下降", displayKeys: "S" },
    { id: "rotateRight", label: "左旋", displayKeys: "A" },
    { id: "rotateLeft", label: "右旋", displayKeys: "D" },
    { id: "stop", label: "悬停", displayKeys: "SPACE" },
  ];
});

const startStatusPolling = () => {
  if (statusTimer.value) {
    clearInterval(statusTimer.value);
    statusTimer.value = null;
  }
  statusTimer.value = setInterval(() => {
    updateDroneStatus();
  }, 5000); // 每5秒更新一次状态
};

const flightDashboardMetrics = computed(() => {
  const data = props.flightDashboardMetrics || {};
  return {
    altitude: data.altitude ?? 0,
    altitudePercent: data.altitudePercent ?? 0,
    heading: data.heading ?? 0,
    pitch: data.pitch ?? 0,
    pitchPercent: data.pitchPercent ?? 0,
    topViewAngle: data.topViewAngle ?? 0,
  };
});

const coordinateText = computed(() => {
  if (!props.selectedDrone) return "坐标未知";
  const { latitude, longitude } = props.selectedDrone;
  if (
    typeof latitude !== "number" ||
    typeof longitude !== "number" ||
    Number.isNaN(latitude) ||
    Number.isNaN(longitude)
  ) {
    return "坐标未知";
  }
  return `纬度 ${latitude.toFixed(6)}，经度 ${longitude.toFixed(6)}`;
});

const toPercent = (value) =>
  `${Number.isFinite(value) ? Math.round(value) : "-"}%`;

// 任务详情相关方法
const getStatusClass = (status) => {
  const statusMap = {
    pending: "status-pending",
    running: "status-running",
    completed: "status-completed",
    failed: "status-failed",
    available: "status-available",
    busy: "status-busy",
    maintenance: "status-maintenance",
    broken: "status-broken",
  };
  return statusMap[status] || "status-default";
};

const getStatusText = (status) => {
  const statusMap = {
    pending: "待执行",
    running: "执行中",
    completed: "已完成",
    failed: "失败",
    available: "可用",
    busy: "忙碌",
    maintenance: "维护中",
    broken: "故障",
  };
  return statusMap[status] || status;
};

const getPriorityText = (priority) => {
  const priorityMap = {
    low: "低",
    medium: "中",
    high: "高",
    urgent: "紧急",
  };
  return priorityMap[priority] || priority;
};

const getExecuteTypeText = (executeType) => {
  const typeMap = {
    real_time: "实时执行",
    scheduled: "计划执行",
    manual: "手动执行",
  };
  return typeMap[executeType] || executeType || "实时执行";
};

const formatTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

const formatCoord = (lat, lng) => {
  if (!lat || !lng) return "";
  return `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
};

// 无人机连接相关方法
const connectDrone = async () => {
  if (!props.selectedDrone) return;

  try {
    controlStatus.value = "connecting";
    controlFeedback.value = "正在连接无人机...";
    const response = await droneService.connectDrone(props.selectedDrone.id);

    if (response.data && response.data.connected) {
      isConnected.value = true;
      droneControlStatus.value = response.data.current_state;
      ElMessage.success("无人机连接成功");
      controlFeedback.value = "连接成功";
      startStatusPolling();
    }
  } catch (error) {
    console.error("连接无人机失败:", error);
    ElMessage.error(error.message || "连接失败");
    controlFeedback.value = "连接失败";
  } finally {
    controlStatus.value = "";
  }
};

const disconnectDrone = async () => {
  if (!props.selectedDrone || !isConnected.value) return;

  try {
    controlStatus.value = "disconnecting";
    controlFeedback.value = "正在断开连接...";
    const response = await droneService.disconnectDrone(props.selectedDrone.id);

    if (response.data && response.data.disconnected) {
      isConnected.value = false;
      droneControlStatus.value = "idle";
      ElMessage.success("无人机断开连接成功");
      controlFeedback.value = "断开连接成功";
      stopStatusPolling();
    }
  } catch (error) {
    console.error("断开连接失败:", error);
    ElMessage.error(error.message || "断开连接失败");
    controlFeedback.value = "断开连接失败";
  } finally {
    controlStatus.value = "";
  }
};

// 发送控制命令
const sendDroneCommand = async (command, parameters = {}) => {
  if (!props.selectedDrone || !isConnected.value) {
    ElMessage.warning("请先连接无人机");
    return;
  }

  console.log("发送命令:", command, parameters);

  try {
    // 确保参数格式正确，特别是方向控制命令
    if (command === "move" && parameters && !parameters.direction) {
      parameters = { ...parameters, direction: "forward" };
    }

    controlStatus.value = "executing";
    controlFeedback.value = `正在执行${getCommandName(command)}...`;

    let response;
    // 特殊处理起飞命令，调用drone-control-px4的mission update接口
    if (command === "takeoff") {
      // 构建起飞任务的payload
      const takeoffPayload = {
        drone_id: props.selectedDrone.id,
        mission_id: Date.now(), // 使用时间戳作为任务ID
        action: 1, // LOAD操作
        mission: JSON.stringify({
          target: "px4",
          plan: [
            {
              behavior: "takeoff",
              method: "__call__",
              args: {
                height: props.droneForm.altitude || 10,
                speed: props.droneForm.speed || 3,
                wait: true,
              },
            },
          ],
        }),
      };

      // 发送LOAD请求
      const loadResult = await droneService.updatePx4Mission(takeoffPayload);
      console.log("起飞任务加载结果:", loadResult);

      // 如果加载成功，发送START请求
      if (isApiSuccess(loadResult)) {
        const startPayload = {
          drone_id: props.selectedDrone.id,
          mission_id: takeoffPayload.mission_id,
          action: 2, // START操作
        };

        response = await droneService.updatePx4Mission(startPayload);
        console.log("起飞任务启动结果:", response);
      } else {
        // 加载失败，使用加载响应作为最终响应
        response = loadResult;
      }
    } else {
      // 其他命令仍然使用原有的droneService
      response = await droneService.sendDroneCommand(
        props.selectedDrone.id,
        command,
        parameters
      );
    }

    // 检查响应状态
    if (isApiSuccess(response)) {
      droneControlStatus.value = getCommandStatus(command);
      const successMessage = getApiMessage(response, "命令执行成功");
      ElMessage.success(successMessage);
      controlFeedback.value = successMessage;
      // 立即更新无人机状态
      updateDroneStatus();
    } else {
      const errorMessage = getApiMessage(response, "命令执行失败");
      ElMessage.error(errorMessage);
      controlFeedback.value = errorMessage;
    }
  } catch (error) {
    console.error("发送命令失败:", error);
    ElMessage.error(error.message || "命令发送失败");
    controlFeedback.value = "命令发送失败";
  } finally {
    controlStatus.value = "";
  }
};

// 更新无人机状态的函数
const updateDroneStatus = async () => {
  if (!props.selectedDrone?.id) return;

  try {
    // 特殊处理：对于ID为2的无人机（PX4无人机），在起飞后直接访问mission_status接口
    const isPX4Drone = props.selectedDrone.id === 2;
    const isFlying = droneControlStatus.value === "flying" || isConnected.value;

    if (isPX4Drone) {
      const px4Alias = getPx4Alias() || "uav_1";
      // 直接调用drone-control-px4的mission_status接口
      const px4Data = await droneService.getPx4MissionStatus("uav_1");
      console.log("PX4无人机任务状态更新:", px4Data);

      if (
        (px4Data.code === undefined || px4Data.code === 200) &&
        px4Data.data
      ) {
        // 更新飞行状态
        const missionState = px4Data.data.state;
        if (missionState) {
          // 映射mission状态到控制状态
          const statusMap = {
            running: "flying",
            completed: "idle",
            paused: "hover",
            failed: "error",
          };
          droneControlStatus.value = statusMap[missionState] || missionState;
        }

        // 更新连接状态
        isConnected.value = true;

        // 保留执行状态，只在首次设置或需要时更新
        // 如果controlFeedback为空，设置任务状态信息
        if (!controlFeedback.value) {
          controlFeedback.value = `任务状态: ${
            px4Data.data.state || "unknown"
          }`;
        }
        // 否则保留原有信息，不覆盖
      }

      // 增加查询pose数据
      try {
        const poseData = await droneService.getPx4Pose("uav_1");
        console.log("PX4无人机姿态数据更新:", poseData);

        // 保存pose数据到变量中
        if (poseData.code === 200 && poseData.data) {
          // 假设存在一个变量用于存储pose数据
          dronePoseData.value = poseData.data;

          // 可以根据需要更新UI显示，例如位置信息
          if (poseData.data.position) {
            const pos = poseData.data.position;
            controlFeedback.value = ` | 位置: X=${pos.x?.toFixed(
              2
            )}, Y=${pos.y?.toFixed(2)}, Z=${pos.z?.toFixed(2)}`;
          }
        } else if (!poseData.code) {
          // 处理非标准格式的响应（可能是直接返回的数据）
          dronePoseData.value = poseData;

          if (poseData.position) {
            const pos = poseData.position;
            controlFeedback.value = ` | 位置: X=${pos.x?.toFixed(
              2
            )}, Y=${pos.y?.toFixed(2)}, Z=${pos.z?.toFixed(2)}`;
          }
        }
      } catch (poseError) {
        console.error("获取无人机姿态数据失败:", poseError);
        // 不影响主流程，继续执行
      }
    } else {
      // 其他情况继续使用原来的接口
      const response = await droneService.getDroneControlStatus(
        props.selectedDrone.id
      );
      if (response.code === 200 && response.data) {
        // 更新无人机的状态信息
        console.log("无人机状态更新:", response.data);
        // 更新连接状态和飞行状态
        if (response.data.is_connected !== undefined) {
          isConnected.value = response.data.is_connected;
        }
        if (response.data.flight_status) {
          droneControlStatus.value = response.data.flight_status;

          // 保留执行状态，不清除
          // 如果controlFeedback为空，可以设置一个默认的状态信息
          if (!controlFeedback.value) {
            const statusMap = {
              flying: "飞行中",
              idle: "待命",
              hover: "悬停",
              error: "错误",
            };
            controlFeedback.value = `飞行状态: ${
              statusMap[response.data.flight_status] ||
              response.data.flight_status
            }`;
          }
        }
        // 更新其他状态信息（如果需要）
        if (response.data.battery_level) {
          props.droneForm.batteryLevel = response.data.battery_level;
        }
      }
    }
  } catch (error) {
    console.error("更新无人机状态失败:", error);
    // 出错时不改变连接状态，避免影响正常操作
    // 保留执行状态，不清除
  }
};

// 紧急控制方法
const handleEmergencyLand = () => {
  sendDroneCommand("land");
};

const handleReturnToHome = () => {
  sendDroneCommand("hover", { action: "return_to_home" });
};

const handlePauseTask = () => {
  sendDroneCommand("takeoff");
};

// 控制点击事件处理
const handleControlClick = async (id) => {
  emit("control-click", id);

  // 根据控制ID映射到对应的无人机命令
  const commandMap = {
    takeoff: () => sendDroneCommand("takeoff"),
    land: () => sendDroneCommand("land"),
    hover: () => sendDroneCommand("hover"),
    forward: () => sendDroneCommand("move", { direction: "forward" }),
    backward: () => sendDroneCommand("move", { direction: "backward" }),
    left: () => sendDroneCommand("move", { direction: "left" }),
    right: () => sendDroneCommand("move", { direction: "right" }),
    ascend: () => sendDroneCommand("move", { direction: "up" }),
    descend: () => sendDroneCommand("move", { direction: "down" }),
    rotateRight: () => sendDroneCommand("rotate", { angle: -45 }),
    rotateLeft: () => sendDroneCommand("rotate", { angle: 45 }),
    stop: () => sendDroneCommand("stop"),
    set_speed: () =>
      sendDroneCommand("set_speed", { speed: props.droneForm.speed || 10 }),
    camera_control: () =>
      sendDroneCommand("camera_control", { action: "capture" }),
  };

  const commandHandler = commandMap[id];
  if (commandHandler) {
    await commandHandler();
  }
};

// 辅助方法
const getCommandName = (command) => {
  const names = {
    takeoff: "起飞",
    land: "降落",
    hover: "悬停",
    move: "移动",
    rotate: "旋转",
    stop: "停止",
    set_speed: "设置速度",
    camera_control: "相机控制",
  };
  return names[command] || command;
};

const getCommandStatus = (command) => {
  if (command === "takeoff") return "flying";
  if (command === "land") return "landing";
  if (command === "stop") return "idle";
  return droneControlStatus.value;
};

// 状态轮询
const pollDroneStatus = async () => {
  if (!props.selectedDrone) return;

  try {
    const response = await droneService.getDroneControlStatus(
      props.selectedDrone.id
    );
    if (response.data) {
      isConnected.value = response.data.is_connected || false;
      droneControlStatus.value = response.data.flight_status || "idle";
      // 更新电池电量信息
      if (response.data.battery_level) {
        props.droneForm.batteryLevel = response.data.battery_level;
      }
      // 更新其他可能的状态信息
      if (response.data.position) {
        console.log("无人机位置:", response.data.position);
      }
    }
  } catch (error) {
    console.error("获取状态失败:", error);
    // 出错时可以考虑将连接状态设置为false
    isConnected.value = false;
  }
};

// 停止状态轮询
const stopStatusPolling = () => {
  if (statusTimer.value) {
    clearInterval(statusTimer.value);
    statusTimer.value = null;
  }
};

// 其他控制方法
const minimizeOverlay = () => {
  isMinimized.value = true;
};

const restoreOverlay = () => {
  isMinimized.value = false;
};

const closeOverlay = () => {
  isMinimized.value = false;
  stopStatusPolling();
  if (isConnected.value) {
    disconnectDrone();
  }
  emit("update:modelValue", false);
};

const handleSubmit = () => emit("submit");

// 生命周期管理
onMounted(() => {
  // 组件挂载时的初始化逻辑
});

onUnmounted(() => {
  // 组件卸载时清理
  stopStatusPolling();
  if (isConnected.value) {
    // 尝试断开连接，但不阻塞卸载
    disconnectDrone().catch(console.error);
  }
});

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      // 对话框显示时开始轮询状态
      startStatusPolling();
      // 初始加载时立即更新一次状态
      updateDroneStatus();
    } else {
      // 对话框关闭时停止轮询
      stopStatusPolling();
      isMinimized.value = false;
    }
  }
);

watch(
  () => props.selectedDrone,
  () => {
    if (props.modelValue) {
      isMinimized.value = false;
    }
  }
);
</script>

<style scoped>
.drone-overlay {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 910;
}

.overlay-panel {
  position: absolute;
  pointer-events: auto;
  background: rgba(15, 23, 42, 0.88);
  border: 1px solid rgba(148, 163, 184, 0.22);
  border-radius: 18px;
  box-shadow: 0 26px 48px rgba(15, 23, 42, 0.55);
  backdrop-filter: blur(18px);
  padding: 12px;
  color: #e5e7eb;
}

.overlay-video {
  left: 45px;
  bottom: 10px;
  width: 380px;
}

.overlay-tabs {
  right: 45px;
  top: 50%;
  width: 380px;
  transform: translateY(-50%);
  transition: transform 0.32s ease;
  display: flex;
  flex-direction: column;
  padding-bottom: 20px;
  height: calc(100vh - 110px);
  overflow-y: scroll;
}
.overlay-tabs.minimized {
  transform: translateY(-50%) translateX(calc(100% + 48px));
  pointer-events: none;
}

.panel-header {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 12px;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #f9fafb;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.status-tag {
  border: none;
}

.video-meta {
  font-size: 12px;
  color: #9ca3af;
}

.video-wrapper {
  position: relative;
  width: 100%;
  height: 190px;
  border-radius: 14px;
  overflow: hidden;
  border: 1px solid rgba(148, 163, 184, 0.18);
  background: rgba(0, 0, 0, 0.6);
}

.video-wrapper video,
.video-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dashboard-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.dashboard-header h4 {
  margin: 0;
  font-size: 18px;
  color: #f9fafb;
}

.dashboard-subtitle {
  font-size: 12px;
  color: #94a3b8;
}

.manual-tab,
.task-detail-tab {
  display: flex;
  flex-direction: column;
  gap: 18px;
  padding: 0;
}

.manual-section {
  padding: 16px;
}

/* 任务详情样式 */
.task-detail-content {
  height: 100%;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 500;
  color: #fff;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.info-item .label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
}

.info-item .value {
  font-size: 14px;
  color: #fff;
  text-align: right;
  flex: 1;
  margin-left: 12px;
}

.description {
  color: #fff;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 无人机列表样式 */
.drone-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.drone-item {
  padding: 12px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.drone-item.primary-drone {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

.drone-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.drone-name {
  color: #fff;
  font-weight: 500;
  font-size: 15px;
}

.primary-badge {
  background: #409eff;
  color: #fff;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.drone-info {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

/* 航线列表样式 */
.route-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.route-item {
  padding: 12px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 6px;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.waypoint-count {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

.waypoints-preview {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.waypoint-item {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  word-break: break-all;
}

.waypoint-more {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 4px;
}

/* 模型列表样式 */
.model-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.model-item {
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 13px;
  color: #fff;
}

/* 进度条样式 */
.progress-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #409eff;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  color: #fff;
  font-size: 14px;
  min-width: 40px;
  text-align: right;
}

/* 状态样式 */
.status-pending {
  color: #e6a23c;
}

.status-running {
  color: #67c23a;
}

.status-completed {
  color: #409eff;
}

.status-failed {
  color: #f56c6c;
}

.status-available {
  color: #67c23a;
}

.status-busy {
  color: #e6a23c;
}

.status-maintenance {
  color: #909399;
}

.status-broken {
  color: #f56c6c;
}

.task-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: rgba(255, 255, 255, 0.5);
  font-size: 14px;
}

.instrument-board {
  display: flex;
  width: 100%;
  gap: 20px;
  align-items: stretch;
  justify-content: space-between;
}

.card {
  background: rgba(15, 23, 42, 0.35);
  border: 1px solid rgba(148, 163, 184, 0.16);
  border-radius: 16px;
  padding: 10px;
  display: flex;
  gap: 12px;
  backdrop-filter: blur(12px);
}

.card.transparent {
  background: rgba(15, 23, 42, 0.18);
}

.manual-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.emergency-controls {
  display: flex;
  gap: 8px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  justify-content: center;
}

.connection-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.board-left {
  display: flex;
  flex: 1;
  gap: 12px;
  align-items: stretch;
}

.metric-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 14px;
  border-radius: 14px;
  border: 1px solid rgba(148, 163, 184, 0.16);
  background: rgba(15, 23, 42, 0.24);
  box-shadow: inset 0 1px 0 rgba(148, 163, 184, 0.08);
}

.metric-label {
  font-size: 13px;
  color: #cbd5f5;
  font-weight: 600;
}

.metric-value {
  font-size: 24px;
  font-weight: 600;
  color: #60a5fa;
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.metric-value span {
  font-size: 14px;
  color: #cbd5f5;
}

.board-right {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 0;
}

.altitude-scale {
  position: relative;
  height: 120px;
  border-radius: 10px;
  background: rgba(96, 165, 250, 0.12);
  overflow: hidden;
}

.altitude-scale-fill {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(180deg, #60a5fa, #1d4ed8);
  transition: height 0.3s ease;
}

.altitude-scale-marker {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 11px;
  color: #cbd5f5;
}

.compass {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.compass-rose {
  width: 130px;
  height: 130px;
  border-radius: 50%;
  border: 2px solid rgba(96, 165, 250, 0.45);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: radial-gradient(
    circle,
    rgba(96, 165, 250, 0.16),
    rgba(15, 23, 42, 0.98)
  );
}

.compass-rose .marker {
  position: absolute;
  font-size: 11px;
  font-weight: 600;
  color: #60a5fa;
}
.compass-rose .north {
  top: 6px;
}
.compass-rose .south {
  bottom: 6px;
}
.compass-rose .east {
  right: 6px;
}
.compass-rose .west {
  left: 6px;
}

.compass-needle {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 60px;
  height: 60px;
  transform-origin: center center;
  pointer-events: none;
}

.compass-readouts {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.compass-value {
  font-size: 18px;
  font-weight: 600;
  color: #f9fafb;
}

.topview-value {
  font-size: 12px;
  color: #cbd5f5;
}

.angle-scale {
  position: relative;
  height: 6px;
  border-radius: 999px;
  background: rgba(96, 165, 250, 0.16);
}

.angle-indicator {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background: linear-gradient(135deg, #60a5fa, #2563eb);
  box-shadow: 0 6px 16px rgba(37, 99, 235, 0.35);
  border: 2px solid rgba(15, 23, 42, 0.9);
}

.tabs-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.tabs-title {
  font-size: 18px;
  font-weight: 600;
  color: #f9fafb;
}

.tabs-actions {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.tabs-action {
  border: none;
  background: transparent;
  color: #9ca3af;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  padding: 4px 6px;
}

.tabs-action:hover {
  color: #e5e7eb;
}

.tabs-minimize {
  font-size: 14px;
}

.tabs-close {
  font-size: 13px;
  color: #9ca3af;
}

.tab-inner {
  display: flex;
  flex-direction: column;
  gap: 16px;
  color: #e5e7eb;
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #cbd5f5;
}

.info-label {
  color: #9ca3af;
}

.params-form {
  background: rgba(23, 31, 50, 0.78);
  border: 1px solid rgba(148, 163, 184, 0.16);
  border-radius: 12px;
  padding: 12px 14px;
}

:deep(.params-form .el-form-item) {
  margin-bottom: 14px;
}

.unit {
  margin-left: 10px;
  font-size: 12px;
  color: #94a3b8;
}

.params-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tabs__nav-wrap::after) {
  background-color: transparent;
}

:deep(.el-tabs__item) {
  color: #cbd5f5;
  font-weight: 500;
  padding: 0 18px;
}

:deep(.el-tabs__item.is-active) {
  color: #60a5fa;
}

:deep(.el-tabs__active-bar) {
  background-color: #60a5fa;
}

.manual-control-head {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.manual-control-head h4 {
  margin: 0;
  font-size: 16px;
  color: #f9fafb;
}

.manual-subtitle {
  font-size: 12px;
  color: #94a3b8;
}

.manual-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(65px, 1fr));
  gap: 10px;
}

.manual-item {
  border: 1px solid rgba(148, 163, 184, 0.22);
  border-radius: 10px;
  padding: 8px 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  background: rgba(15, 23, 42, 0.7);
  transition: all 0.2s ease;
}

.manual-item:hover {
  border-color: rgba(96, 165, 250, 0.6);
  box-shadow: 0 8px 16px rgba(37, 99, 235, 0.18);
}

.manual-item.active {
  border-color: rgba(96, 165, 250, 0.9);
  background: rgba(37, 99, 235, 0.24);
  box-shadow: 0 10px 20px rgba(37, 99, 235, 0.24);
}

.control-name {
  font-size: 13px;
  color: #f9fafb;
}

.control-keys {
  font-size: 11px;
  color: #93c5fd;
}

.manual-feedback {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 12px 14px;
  border-radius: 12px;
  border: 1px solid rgba(148, 163, 184, 0.16);
  background: rgba(23, 31, 50, 0.78);
}

.feedback-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #cbd5f5;
}

.feedback-label {
  color: #94a3b8;
}

.feedback-value {
  color: #f9fafb;
}

.drone-overlay-enter-active,
.drone-overlay-leave-active {
  transition: opacity 0.24s ease;
}

.drone-overlay-enter-from,
.drone-overlay-leave-to {
  opacity: 0;
}

.overlay-expand-button {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  background: rgba(15, 23, 42, 0.92);
  border: 1px solid rgba(148, 163, 184, 0.36);
  border-radius: 14px 0 0 14px;
  color: #e5e7eb;
  padding: 20px 4px;
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
  letter-spacing: 2px;
  pointer-events: auto;
  writing-mode: vertical-rl;
  text-orientation: mixed;
  box-shadow: 0 18px 30px rgba(15, 23, 42, 0.48);
  z-index: 915;
}

.overlay-expand-button:hover {
  color: #f9fafb;
  background: rgba(30, 41, 59, 0.95);
}
</style>
